package org.pub.fast.jdbc.page;

public class DB2LimitSQLBuilder implements LimitSQLBuilder {
    public String build(String sql, int pageIndex, int pageSize) {
        StringBuffer rownumber = new StringBuffer(50)
                .append(" rownumber() over(");
        int orderByIndex = sql.toLowerCase().indexOf("order by");
        if (orderByIndex > 0) rownumber.append(sql.substring(orderByIndex));
        rownumber.append(") as row_,");
        StringBuffer pagingSelect = new StringBuffer(sql.length() + 100)
                .append("select * from ( ")
                .append(sql)
                .insert(getAfterSelectInsertPoint(sql), rownumber.toString())
                .append(" ) as temp_ where row_ ");

        pagingSelect.append("between " + ((pageIndex - 1) * pageSize + 1) + " and " + pageIndex * pageSize);

        return pagingSelect.toString();
    }

    private static int getAfterSelectInsertPoint(String sql) {
        return 16 + (sql.startsWith("select distinct") ? 15 : 6);
    }

    public static void main(String[] args) {
        DB2LimitSQLBuilder builder = new DB2LimitSQLBuilder();
        String s = builder.build("select * from tt", 2, 10);
        System.out.println(" " + s);
    }
}

